<template>
  <div class="publish-news-container">
    <el-card class="publish-card">
      <template #header>
        <div class="card-header">
          <span>发布公告</span>
        </div>
      </template>

      <el-form :model="publishForm" label-width="80px" ref="publishFormRef">
        <el-form-item
          label="标题"
          prop="title"
          :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
        >
          <el-input
            v-model="publishForm.title"
            placeholder="请输入新闻标题"
            size="large"
          />
        </el-form-item>

        <el-form-item
          label="正文"
          prop="content"
          :rules="[{ required: true, message: '请输入正文', trigger: 'blur' }]"
        >
          <el-input
            v-model="publishForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入新闻正文"
            size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitPublish"
            size="large"
            :loading="publishLoading"
          >
            发布新闻
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import api from "@/util/service";
import { useLoginStore } from "@/stores/userStores";
import { ElMessage } from "element-plus";

const userStore = useLoginStore();
const userid = userStore.getId;

const publishFormRef = ref(null);
const publishLoading = ref(false);

const publishForm = reactive({
  userid: userid,
  title: "",
  content: "",
});

const submitPublish = async () => {
  // 表单验证
  await publishFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        publishLoading.value = true;
        const res = await api.post("/tnews/insertNews", publishForm);

        if (res.code === 200) {
          ElMessage({
            message: "新闻发布成功!",
            type: "success",
          });

          // 清空表单
          publishForm.title = "";
          publishForm.content = "";
        } else {
          ElMessage({
            message: "发布失败: " + (res.message || ""),
            type: "error",
          });
        }
      } catch (error) {
        ElMessage({
          message: "发布失败，请稍后重试!",
          type: "error",
        });
        console.error("Publish error:", error);
      } finally {
        publishLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.publish-news-container {
  display: flex;
  justify-content: center;
  padding: 30px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.publish-card {
  width: 100%;
  max-width: 800px;
}

.card-header {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

.el-form {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: 500;
}
</style>
